package com.mathassistant.server.domain;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.mathassistant.server.PMF;
import com.mathassistant.shared.UserDTO;
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class UserAccount {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
	private String key;
	
	@Persistent
	private String email;
	
	@Persistent
	private String name;
	
	@Persistent
	private String password;
	
	@Persistent
	private boolean isAdmin;
	
	public UserAccount(){
		this("default@test.com","Administrator","administrator",true);
	}
	
	public UserAccount(UserDTO user){
		this(user.getEmail(), user.getName(),user.getPassword(),user.isAdmin());
	}
	
	public UserAccount (String email, String name, String password, boolean admin){
		this.setEmail(email);
		this.setName(name);
		this.setPassword(password);
		this.setAdmin(admin);
	}
	
	public String getKey(){
		return key;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	public String getEmail() {
		return email;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}
	public boolean isAdmin() {
		return isAdmin;
	}
	
	public static UserAccount getDefaultUser(){
		String defaultEmail = "default@test.com";
	    
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    
	    UserAccount result = null;
	    try {
	    	Query q = pm.newQuery(UserAccount.class, "emailAddress == :email");
	    	q.setUnique(true);
	    	result = (UserAccount) q.execute(defaultEmail);
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        pm.close();
	    }
	    return result;
	}
	
	public static UserDTO toDTO(UserAccount user){
		if(user == null)
			return null;
		return new UserDTO(user.getKey(),user.getName(), user.getPassword(),user.getEmail(),user.isAdmin());
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}
}
